package com.gitee.chenyaohua.conn;

import com.gitee.chenyaohua.utils.StringUtils;
import org.apache.commons.pool2.ObjectPool;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DbUtils {



    private  ObjectPool<Connection> objectPool;

    public DbUtils(ObjectPool<Connection> objectPool) {
        this.objectPool = objectPool;
    }

    public List<Map<String,Object>> select(String sql,Object ...args){
        Connection connection = null;
        List<Map<String,Object>> queryResult = null;
        try {
             //获取连接
            connection = objectPool.borrowObject();
            PreparedStatement statement = connection.prepareStatement(sql);
            if(args != null && args.length!=0){
                for (int i = 0; i < args.length; i++) {
                    statement.setObject(i+1,args[i]);
                }
            }
            ResultSet resultSet = statement.executeQuery();
            queryResult = getQueryResult(resultSet);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //归还连接
                objectPool.returnObject(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return queryResult;
    }

    private List<Map<String,Object>> getQueryResult(ResultSet resultSet) throws SQLException {
        List<Map<String,Object>> list = new ArrayList<>();

        Map<String,Object> map = null;
        while (resultSet.next()) {
            map = new HashMap<>();
            ResultSetMetaData metaData1 = resultSet.getMetaData();
            int columnCount = metaData1.getColumnCount();
            for (int i = 0; i < columnCount; i++) {
                String columnName = metaData1.getColumnName(i + 1);
                String columnLabel = metaData1.getColumnLabel(i + 1);
                Object object = resultSet.getObject(StringUtils.defaultIfEmpty(columnLabel,columnName));
                map.put(StringUtils.defaultIfEmpty(columnLabel,columnName),object);
            }
            list.add(map);
        }
        return list;
    }

    public String queryDBType(){
        Connection connection = null;
        try {
             //获取连接
            connection = objectPool.borrowObject();
            DatabaseMetaData metaData = connection.getMetaData();
            String databaseProductName = metaData.getDatabaseProductName();
            return databaseProductName.trim().toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //归还连接
                objectPool.returnObject(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
